package com.platform.qujia.service.impl;

import com.platform.qujia.constantEnum.integralTypeEnum;
import com.platform.qujia.controller.CouponController;
import com.platform.qujia.dao.AppUserInfoMapper;
import com.platform.qujia.dao.CustomerCardSettingDetailContentMapper;
import com.platform.qujia.dao.CustomerCardUseRecordMapper;
import com.platform.qujia.dao.ElectronicMembershipCardMapper;
import com.platform.qujia.enums.CardRecordType;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.LocalDateTimeUtil;
import com.platform.qujia.utils.MathUtil;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("electronicMembershipCardService")
public class ElectronicMembershipCardServiceImpl implements ElectronicMembershipCardService {

    private static final Logger log = LoggerFactory.getLogger(ElectronicMembershipCardServiceImpl.class);

    @Resource
    private ElectronicMembershipCardMapper electronicMembershipCardMapper;

    @Resource
    private CustomerCardSettingDetailContentMapper customerCardSettingDetailContentMapper;

    @Lazy
    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Autowired
    private CustomerPointsRecordService customerPointsRecordService;
    @Autowired
    private CustomerCardSettingDetailService customerCardSettingDetailService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private CouponController couponController;
    @Autowired
    private ReductionActivityBalanceRecordService reductionActivityBalanceRecordService;
    @Autowired
    private WxPushUtil wxPushUtil;
    @Autowired
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;

    @Resource
    private WeChatService weChatService;

    //根据小程序用户openId查询客户电子会员卡信息-
    @Override
    public CustomerElectronicCard getElectronicCardInfoByMinaOpenId(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.getElectronicCardInfoByMinaOpenId(customerElectronicCard);
    }

    //插入电子会员卡
    @Override
    public void insetElectronicCard(CustomerElectronicCard customerElectronicCard) {
        electronicMembershipCardMapper.insetElectronicCard(customerElectronicCard);
    }

    //根据unionId和油品类型获取用户用要充值电子会员卡(储蓄卡)信息
    @Override
    public CustomerElectronicCard getElectronicCardInfoByPhone(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.getElectronicCardInfoByPhone(customerElectronicCard);
    }

    //查询油站电子会员卡（储蓄卡）充值设置规则
    @Override
    public List<CustomerCardSetting> getCardRechargeSettingList(CustomerCardSetting customerCardSetting) {
        List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardMapper.getCardRechargeSettingList(customerCardSetting);
        for (CustomerCardSetting cardSetting : cardRechargeSettingList) {
            CustomerCardSettingDetail detail=new CustomerCardSettingDetail();
            detail.setParentId(cardSetting.getId());
            detail.setCardType(customerCardSetting.getCardOilsType());
            detail.setEnterpriseId(customerCardSetting.getEnterpriseId().longValue());
            detail.setStationId(customerCardSetting.getStationId().longValue());
            detail.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
            List<CustomerCardSettingDetail> customerCardSettingDetailList=electronicMembershipCardMapper.getDetailAndContent(detail);
            customerCardSettingDetailList=customerCardSettingDetailList.stream().filter(d->customerCardSettingDetailService.checkEffectiveTime(d)).collect(Collectors.toList());
            List<CustomerCardSettingDetail> collect = customerCardSettingDetailList.stream().filter(m -> m.getActivityType().equals(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE)).collect(Collectors.toList());
            List<CustomerCardSettingDetail> collect1 = customerCardSettingDetailList.stream().filter(m -> m.getActivityType().equals(CustomerCardSettingDetail.ACTIVITYTYPE_COUPON)).collect(Collectors.toList());
            cardSetting.setCustomerCardSettingDetailList(collect);
            cardSetting.setCustomerCardSettingDetailCouponList(collect1);
        }
        return cardRechargeSettingList;
    }

    //根据unionId更新客户余额
    @Override
    public void updateElectronicCardInfoByPhone(CustomerElectronicCard customerElectronicCard) {
        electronicMembershipCardMapper.updateElectronicCardInfoByPhone(customerElectronicCard);
    }

    //查询油站的会员卡启用标识 （1、启动 2，停用)
    @Override
    public String getStationCardEnabledFlag(Integer stationId) {
        return electronicMembershipCardMapper.getStationCardEnabledFlag(stationId);
    }

    //根据订单号查询用户的充值记录
    @Override
    public CustomerCardUseRecord getCardRecordByOrderNo(CustomerCardUseRecord customerCardUseRecord) {
        return electronicMembershipCardMapper.getCardRecordByOrderNo(customerCardUseRecord);
    }

    //根据商户订单号查询用户的充值记录
    @Override
    public CustomerCardUseRecord getCardRecordByMerchantsNumber(CustomerCardUseRecord customerCardUseRecord) {
        return electronicMembershipCardMapper.getCardRecordByMerchantsNumber(customerCardUseRecord);
    }

    //根据订单号更新客户充值记录
    @Override
    public void updateCardRecordStatusByOrderNo(CustomerCardUseRecord customerCardUseRecord) {
        electronicMembershipCardMapper.updateCardRecordStatusByOrderNo(customerCardUseRecord);
    }

    //获取用户储蓄卡的使用记录
    @Override
    public List<CustomerCardUseRecord> getCardUseRecordList(CustomerCardUseRecord customerCardUseRecord) {
        return electronicMembershipCardMapper.getCardUseRecordList(customerCardUseRecord);
    }

    //获取用户储蓄卡列表
    @Override
    public List<CustomerElectronicCard> getElectronicCardListBycardOilsTypeArray(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.getElectronicCardListBycardOilsTypeArray(customerElectronicCard);
    }

    //获取用户储蓄卡列表
    @Override
    public List<CustomerElectronicCard> getElectronicCardList(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.getElectronicCardList(customerElectronicCard);
    }

    //更新电子会员卡（储蓄卡）的信息
    @Override
    public void updateElectronicCardInfo(CustomerElectronicCard customerElectronicCard) {
        electronicMembershipCardMapper.updateElectronicCardInfo(customerElectronicCard);
    }

    //新增电子会员卡的充值使用记录
    @Override
    public void insetCardUseRecordRecharge(CustomerCardUseRecord customerCardUseRecord) {
        electronicMembershipCardMapper.insetCardUseRecordRecharge(customerCardUseRecord);
    }
    //修改电子会员卡的充值使用记录
    @Override
    public void updateCardUseRecordRecharge(CustomerCardUseRecord customerCardUseRecord) {
        electronicMembershipCardMapper.updateCardUseRecordRecharge(customerCardUseRecord);
    }

    //新增电子会员卡的消费使用记录
    @Override
    public void insetCardUseRecordConsumption(CustomerCardUseRecord customerCardUseRecord) {
        electronicMembershipCardMapper.insetCardUseRecordConsumption(customerCardUseRecord);
    }

    //获取活用要充值电子会员卡的信息
    @Override
    public CustomerElectronicCard getElectronicCardInfo(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.getElectronicCardInfo(customerElectronicCard);
    }
    @Override
    //查询电子卡的最低充值金额
    public List<CustomerCardSetting> getCardRechargeMinAmt(CustomerCardSetting customerCardSetting){
        return electronicMembershipCardMapper.getCardRechargeMinAmt(customerCardSetting);
    }

    @Override
    public CustomerElectronicCard getAndCreateCustomerElectronicCard(AppUserInfo appUserInfos, String cardType, Station station) {
        CustomerElectronicCard customerElectronicCard = this.getCustomerElectronicCard(appUserInfos, cardType, station);
        if(null != customerElectronicCard){
            //存在
            return customerElectronicCard;
        }else {
            //不存在
            CustomerElectronicCard ces = new CustomerElectronicCard();
            ces.setCreateTime(new Date());
            ces.setAmt(BigDecimal.ZERO);
            ces.setCardOilsType(cardType);
            ces.setCustomerNo(appUserInfos.getMemberCode());
            ces.setMobilePhone(appUserInfos.getMobilePhone());
            ces.setPresentAmt(BigDecimal.ZERO);
            ces.setReturnCashAmt(BigDecimal.ZERO); // 设置返利金
            if (StringUtils.equals("1",station.getEnterprise().getCardUseRangeFlag())) {
                ces.setStationId(station.getEnterpriseId());
            }else{
                ces.setStationId2(station.getStationId());
            }
            electronicMembershipCardMapper.insetElectronicCard(ces);
            return ces;
        }
    }

    @Override
    public CustomerElectronicCard getCustomerElectronicCard(AppUserInfo appUserInfos, String cardType, Station station) {
        if (station == null || station.getEnterprise() == null) {
            throw new CustomException("油企或油站为空");
        }

        log.info("查询用户电子卡，油企ID:{},单子卡使用范围:{},油站ID:{},卡类型:{},手机号:{}",
                station.getEnterpriseId(),station.getEnterprise().getCardUseRangeFlag(),station.getStationId(),cardType,appUserInfos.getMobilePhone());

        CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                .cardOilsType(cardType)
                .mobilePhone(appUserInfos.getMobilePhone());

        if (StringUtils.equals("1",station.getEnterprise().getCardUseRangeFlag())) {
            builder.stationId(station.getEnterpriseId());
        }else{
            builder.stationId2(station.getStationId());
        }
        return electronicMembershipCardMapper.getElectronicCardInfoByPhone(builder.build());
    }

    @Override
    public List<CustomerElectronicCard> getCustomerElectronicCardListForEnterprise(String mobilePhone, String[] cardTypes, Integer enterpriseId){
        CustomerElectronicCard card = CustomerElectronicCard.builder()
                .mobilePhone(mobilePhone)
                .cardOilsTypeArray(cardTypes)
                .stationId(enterpriseId)
                .build();
        return this.getElectronicCardListBycardOilsTypeArray(card);
    }

    @Override
    public List<CustomerElectronicCard> getCustomerElectronicCardListForStation(String mobilePhone, String[] cardTypes, Integer stationId){
        CustomerElectronicCard card = CustomerElectronicCard.builder()
                .mobilePhone(mobilePhone)
                .cardOilsTypeArray(cardTypes)
                .stationId2(stationId)
                .build();
        return this.getElectronicCardListBycardOilsTypeArray(card);
    }

    @Override
    public List<CustomerElectronicCard> queryCustomerElectronicCardList(String mobilePhone, String[] cardTypes, Station station){
        if (station == null || station.getEnterprise() == null) {
            throw new CustomException("油企或油站为空");
        }

        if (StringUtils.equals("1",station.getEnterprise().getCardUseRangeFlag())) {
            return getCustomerElectronicCardListForEnterprise(mobilePhone, cardTypes,station.getEnterpriseId());
        }else{
            return getCustomerElectronicCardListForStation(mobilePhone,cardTypes, station.getStationId());
        }
    }

    @Override
    public void updateElectronicCardInfoByPhone(CustomerElectronicCard.CustomerElectronicCardBuilder builder,Station station) {

        if (station == null || station.getEnterprise() == null) {
            throw new CustomException("油企或油站为空");
        }

        if (StringUtils.equals("1",station.getEnterprise().getCardUseRangeFlag())) {
            builder.stationId(station.getEnterprise().getEnterpriseId());
        }else{
            builder.stationId2(station.getStationId());
        }
        electronicMembershipCardMapper.updateElectronicCardInfoByPhone(builder.build());
    }

    @Override
    public BigDecimal getCustomerElectronicCardBalance(String mobilePhone, Integer enterpriseId, boolean cardUseForAll, List<String> types) {
        BigDecimal balance = electronicMembershipCardMapper.countCardBalance(mobilePhone,enterpriseId,cardUseForAll,types);
        return balance == null ? BigDecimal.ZERO : balance;
    }

    @Override
    public List<CustomerCardSettingDetail> selectCardSettingDetail(CustomerCardSettingDetail customerCardSettingDetail) {
        return electronicMembershipCardMapper.selectCardSettingDetail(customerCardSettingDetail);
    }

    @Override
    public List<CustomerCardSettingDetailContent> getCardSettingDetailContents(CustomerCardSettingDetailContent contentQuery) {
        return customerCardSettingDetailContentMapper.query(contentQuery);
    }

    //获得因冻结充值活动而冻结的金额
    @Override
    public BigDecimal getFreezePresentAmt(CustomerCardUseRecord useRecordQuery) {
        if(useRecordQuery.getMobilePhone()==null){
            return BigDecimal.ZERO;
        }
        if(useRecordQuery.getEnterpriseId()==null&&useRecordQuery.getStationId()==null){
            return BigDecimal.ZERO;
        }
        BigDecimal freezePresentAmt = electronicMembershipCardMapper.getFreezePresentAmt(useRecordQuery);
        if(freezePresentAmt==null){
            freezePresentAmt=BigDecimal.ZERO;
        }
        return freezePresentAmt;
    }

    @Override
    public boolean isNonpayment(String mobilePhone,Station station,BigDecimal amt,BigDecimal balance) {
        //查询是否有冻结的赠送金额
        CustomerCardUseRecord useRecordQuery=new CustomerCardUseRecord();
        useRecordQuery.setMobilePhone(mobilePhone);

        if (StringUtils.equals("1",station.getEnterprise().getCardUseRangeFlag())) {
            useRecordQuery.setEnterpriseId(station.getEnterpriseId());
        }else{
            useRecordQuery.setStationId(station.getStationId());
        }
        BigDecimal freezePresentAmt = getFreezePresentAmt(useRecordQuery);
        BigDecimal subtractBalance = balance.subtract(freezePresentAmt);
        if(subtractBalance.compareTo(BigDecimal.ZERO)==-1){
            subtractBalance=BigDecimal.ZERO;
        }
        if(amt.compareTo(subtractBalance)>0){
            throw new CustomException("部分赠送金额被冻结,实际余额为:"+subtractBalance.toString()+"元");
        }
        return false;
    }

    @Override
    public CustomerCardUseRecord selectCustomerCardUseRecordByOrderNo(String orderNo) {
        return electronicMembershipCardMapper.selectCustomerCardUseRecordByOrderNo(orderNo);
    }

    public List<CustomerCardSettingDetailContent> queryCardSettingDetailContentsByCcsdIdsBetweenAmt(List<Integer> ccsdIds,BigDecimal amt){
        return customerCardSettingDetailContentMapper.queryListByCcsdIdsBetweenAmt(ccsdIds,amt);
    }

    @Override
    public Integral rechargeActivityGiveIntegral(String orderNo) {
        Integral integral=new Integral();
        integral.setTotalIntegral(0);
        integral.setPresentIntegral(0);

        CustomerCardUseRecord recordQuery = new CustomerCardUseRecord();
        recordQuery.setOrderNo(orderNo);
        CustomerCardUseRecord cardRecordByOrderNo = getCardRecordByOrderNo(recordQuery);
        integral=rechargeActivityGiveIntegral(cardRecordByOrderNo);
        return integral;
        }


    @Override
    public Integral rechargeActivityGiveIntegral(CustomerCardUseRecord cardRecordByOrderNo) {
        Integral integral=new Integral();
        integral.setTotalIntegral(0);
        integral.setPresentIntegral(0);
        CustomerCardSettingDetail form = new CustomerCardSettingDetail();

        form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_INTEGRAL);//积分
        form.setDelFlag("0");
        form.setCardType(cardRecordByOrderNo.getCardOilsType());
        form.setEnterpriseId(Long.valueOf(cardRecordByOrderNo.getEnterpriseId()));
        form.setStationId(Long.valueOf(cardRecordByOrderNo.getStationId()));
        form.setStatus("NORMAL");
        if(cardRecordByOrderNo.getPayType()==null){
            cardRecordByOrderNo.setPayType("xj");
        }
        String payType = cardRecordByOrderNo.getPayType();
        if (StringUtils.equals(CardRecordType.MANUAL_ADD.getKey(),payType)) {
            payType = "xj";
        }
        if (StringUtils.equals(CardRecordType.POS_RECHARGE.getKey(), payType)) {
            payType = "wx";
        }
        form.setPayType(payType);
        form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);

        //form.setAmt(amt);
        form.setNowDate(new Date());
        form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
        form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));

        AppUserInfo appUserInfo=new AppUserInfo();
        appUserInfo.setMobilePhone(cardRecordByOrderNo.getMobilePhone());
        appUserInfo.setStationId(cardRecordByOrderNo.getEnterpriseId());
        List<AppUserInfo> appUserInfos = appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);
        if(appUserInfos.size()>0) {
            appUserInfo=appUserInfos.get(0);
        }else{
            return integral;
        }

        BigDecimal amt = cardRecordByOrderNo.getAmt();
        if(amt !=null){
            //CustomerCardSettingDetailContent content=customerCardSettingDetailContentMapper.selectMatchFirstDetailContent(form);
            List<CustomerCardSettingDetail> customerCardSettingDetails = selectCardSettingDetail(form);
            if (!customerCardSettingDetails.isEmpty()) {
                CouponInfoSettingDetail couponInfoSettingDetail = new CouponInfoSettingDetail();
                couponInfoSettingDetail.setEnterpriseId(Long.valueOf(cardRecordByOrderNo.getEnterpriseId()));
                List<Integer> ccsdIds = customerCardSettingDetails.stream().filter(d->customerCardSettingDetailService.checkEffectiveTime(d)).map(CustomerCardSettingDetail::getCardSettingDetailId).collect(Collectors.toList());
                if(ccsdIds.size()>0){
                    List<CustomerCardSettingDetailContent> contentList = queryCardSettingDetailContentsByCcsdIdsBetweenAmt(ccsdIds, amt);
                    for (CustomerCardSettingDetailContent content : contentList) {
                        if (amt.compareTo(content.getRechargeAmtLowerLimit()) >= 0 && amt.compareTo(content.getRechargeAmtUpperLimit()) < 0) {
                            BigDecimal presentAmount = content.getPresentAmount();
                            if(presentAmount==null){
                                return integral;
                            }
                            if(appUserInfo.getUserId()!=null) {
                                Integer totalInteger = appUserInfo.getIntegral();
                                int presentIntegral= presentAmount.multiply(amt).intValue();
                                if (presentIntegral>0) {
                                    if(totalInteger==null){
                                        totalInteger=presentIntegral;
                                    }else{
                                        totalInteger=totalInteger+presentIntegral;
                                    }
                                    appUserInfo.setIntegral(totalInteger);
                                    integral.setPresentIntegral(presentIntegral);
                                    integral.setTotalIntegral(totalInteger);
                                    appUserInfoMapper.updateAppUserInfoByUserId(appUserInfo);
                                    CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                                    customerPointsRecord.setCreateTime(new Date());
                                    customerPointsRecord.setIntegral(presentIntegral);
                                    customerPointsRecord.setOrderNo(cardRecordByOrderNo.getOrderNo());
                                    customerPointsRecord.setRecordType("+");
                                    customerPointsRecord.setMobilePhone(appUserInfo.getMobilePhone());
                                    customerPointsRecord.setUnionId(appUserInfo.getUnionId());
                                    customerPointsRecord.setStationId(cardRecordByOrderNo.getStationId());
                                    customerPointsRecord.setCustomerName(appUserInfo.getBlogNickName());
                                    customerPointsRecord.setAction(integralTypeEnum.CONSUMEPRESENT);
                                    customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);

                                    //同步微信卡包的积分
                                    Enterprise enterprise = enterpriseService.selectEnterpriseInfo(appUserInfo.getStationId());
                                    weChatService.wxAddBonusByUserInfoAndEnterpriseAndAction(integralTypeEnum.CONSUMEPRESENT,appUserInfo,enterprise);
                                }

                                return integral;
                            }
                        }
                    }
                }
            }

        }
        return integral;
    }

    public int incrCustomerElectronicCardBalance(BigDecimal incrAmt, BigDecimal incrPresentAmt, CustomerElectronicCard card){
        return electronicMembershipCardMapper.incrCustomerElectronicCardBalance(incrAmt,incrPresentAmt,card);
    }

    @Override
    @Transactional
    public void sxfDzkRechargeCallback(String payTime, String ordNo, String amt, String transactionId, String payType,String savedPayType,Integer preId) {
        //随行付回调验签成功更新客户电子卡余额 和 更新客户充值记录状态
        CustomerCardUseRecord customerCardUseRecordInfo = getCardRecordByOrderNo(CustomerCardUseRecord.builder().orderNo(ordNo).build());
        // 0表示未支付  1表示已支付
        if(null != customerCardUseRecordInfo  && "0".equals(customerCardUseRecordInfo.getStatus())){
            log.info("充值单号：" + ordNo);
            log.info("充值订单信息{}",customerCardUseRecordInfo);
            //查询客户该油品电子卡信息
            Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
            Enterprise enterprise = station.getEnterprise();
            boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());

            //是否有赠送金额
            BigDecimal presentAmt =BigDecimal.ZERO;
            if(customerCardUseRecordInfo.getPresentAmt() !=null){
                presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                log.info("客户充值赠送金额：" +presentAmt.toString());
            }

            //获取客户充值的得电子卡信息
            log.info("用户手机号：" + customerCardUseRecordInfo.getMobilePhone() + "; 油企ID：" + station.getEnterpriseId() + "; 卡类型：" + customerCardUseRecordInfo.getCardOilsType());
            AppUserInfo userinfo = new AppUserInfo();
            userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
            CustomerElectronicCard electronicCardInfo = getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);
            if(electronicCardInfo !=null){
                if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                    //充值赠额记录
                    customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(), ordNo,
                            PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                }
                BigDecimal manualPresentAmt = BigDecimal.ZERO;
                if (preId != null && preId>0) {
                    // pos机手动输入赠送金额功能
                    CustomerCardUseRecord preRecord = customerCardUseRecordMapper.getById(Long.valueOf(preId));
                    if (preRecord != null) {
                        manualPresentAmt = preRecord.getPresentAmt();
                    }else{
                        preId = null;
                    }
                }

                log.info("客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                BigDecimal afterAmt = electronicCardInfo.getAmt().add(new BigDecimal(amt));
                electronicCardInfo.setAmt(afterAmt);
                BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                electronicCardInfo.setPresentAmt(afterPresentAmt);
                //BigDecimal newBalance = electronicCardInfo.getAmt().add(new BigDecimal(amt)).add(presentAmt);   //客户新的余额
                BigDecimal newBalance = electronicCardInfo.getTotalAmt();

                BigDecimal afterManPresAmt = electronicCardInfo.getPresentAmt().add(manualPresentAmt);
                electronicCardInfo.setPresentAmt(afterManPresAmt);
                BigDecimal afterPresentBalance = electronicCardInfo.getTotalAmt();
                BigDecimal finalPresentAmt = MathUtil.add(presentAmt, manualPresentAmt);

                //电子卡充值方式
                String ccurPayType = "";
                switch (payType){
                    case "WECHAT":
                        ccurPayType ="wx";
                        break;
                    case "ALIPAY":
                        ccurPayType ="zfb";
                        break;
                }
                if (StringUtils.isNotBlank(savedPayType)) {
                    ccurPayType = savedPayType;
                }
                Date payTimeDate;
                if (StringUtils.isNotBlank(payTime)) {
                    try {
                        payTimeDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime);
                    } catch (ParseException e) {
                        payTimeDate = new Date();
                        log.error(e.getMessage(), e);
                    }
                }else{
                    payTimeDate = new Date();
                }
                if(StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null != customerCardUseRecordInfo.getStationId()){
                    //更新充值记录的状态和余额
                    updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                            .payType(ccurPayType)
                            .balance(newBalance)
                            .transactionId(transactionId)
                            .payTime(payTimeDate)
                            .orderNo(ordNo)
                            .status("1")
                            .build());
                    if (preId != null && preId > 0) {
                        // pos机手动输入赠送金额功能
                        electronicMembershipCardMapper.updateCardUseRecordRecharge(CustomerCardUseRecord.builder()
                                .balance(afterPresentBalance)
                                .status("1")
                                .id(preId)
                                .build());
                    }
                    //更新客户余额
                    CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                            .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                            .mobilePhone(electronicCardInfo.getMobilePhone())
                            .recentlyTime(new Date())
                            .amt(afterAmt)
                            .presentAmt(afterManPresAmt);

                    if (cardUsingForAll) {
                        builder.stationId(station.getEnterpriseId());
                    }else{
                        builder.stationId2(station.getStationId());
                    }

                    updateElectronicCardInfoByPhone(builder.build());
                    //更新参与立减活动的优惠余额
                    reductionActivityBalanceRecordService.createBalanceRecord(ordNo,customerCardUseRecordInfo.getCardOilsType(),new BigDecimal(amt),station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");
                    //充值活动发券
                    couponController.sendCounponByCardUserRecord(ordNo);
                    //充值活动送积分
                    Integral integral = rechargeActivityGiveIntegral(ordNo);

                    log.info("客户当前充值后应有金额：" + newBalance.toString());
                    log.info("===========客户电子会员卡充值成功已到账====");

                    //充值订单打印小票
                    customerCardUseRecordInfo.setPayType(payType);
                    customerCardUseRecordInfo.setIntegral(integral.getPresentIntegral());
                    if (preId != null && preId > 0) {
                        customerCardUseRecordInfo.setPresentAmt(finalPresentAmt);
                        customerCardUseRecordInfo.setBalance(afterPresentBalance);
                    }
                    gzhNewsTemplateService.elecOrderPush(customerCardUseRecordInfo);

                    //微信模板消息推送充值成功模板
                    if ("WECHAT".equals(payType)) {
                        Map<String, String> templateParams = new HashMap<>();
                        templateParams.put("openid", customerCardUseRecordInfo.getBlogOpenid());
                        templateParams.put("customerNo", electronicCardInfo.getCustomerNo());
                        templateParams.put("amt", amt + "元");
                        templateParams.put("presentAmt", finalPresentAmt + "元");
                        templateParams.put("balance", afterPresentBalance + "元");
//                            String cardName = "";
//                            switch (customerCardUseRecordInfo.getCardOilsType()) {
//                                case "0":
//                                    cardName = "通用卡";
//                                    break;
//                                case "1":
//                                    cardName = "汽油卡";
//                                    break;
//                                case "2":
//                                    cardName = "柴油卡";
//                                    break;
//                                case "3":
//                                    cardName = "LNG卡";
//                                    break;
//                                case "4":
//                                    cardName = "CNG卡";
//                                    break;
//                            }
//                            templateParams.put("type", "微信支付-" + cardName);
                        log.info("电子卡充值-微信模板参数：{}", templateParams);
                        wxPushUtil.sendTemplateMsg(station.getEnterpriseId(), templateParams, WxTemplateEnum.RECHARGE_SUCCESS);
                        if (integral.getPresentIntegral()>0) {
                            Map<String, String> integralParams = new HashMap<>();
                            integralParams.put("openid", customerCardUseRecordInfo.getBlogOpenid());
                            integralParams.put("stationName", station.getStationName());
                            integralParams.put("createTime", LocalDateTimeUtil.parse(LocalDateTime.now()));
                            integralParams.put("integral", String.valueOf(MathUtil.add(null,integral.getPresentIntegral())));
                            integralParams.put("totalIntegral", String.valueOf(MathUtil.add(null,integral.getTotalIntegral())));
                            wxPushUtil.sendTemplateMsg(station.getEnterpriseId(),integralParams,WxTemplateEnum.INTEGRAL_CHANGE);
                        }
                    }

//                        GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder()
//                                .stationId(station.getEnterpriseId())
//                                .templateType("3")      //3 代表电子会员卡充值成功模板类型
//                                .build());
//                        if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
//                            log.info("当前要推送消息所用使用的模板ID："+ gzhNewsTemplateInfo.getTemplateId());
//                            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
//                            if(enterprise !=null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())){
//                                String gzhAppId = enterprise.getGzhAppId();
//                                String gzhAppSecret = enterprise.getGzhAppSecret();
//                                //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
//                                if(StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())){
//                                    //List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
//                                    String cardName = "";
//                                    switch (customerCardUseRecordInfo.getCardOilsType()){
//                                        case "0":
//                                            cardName = "通用";
//                                            break;
//                                        case "1":
//                                            cardName = "汽油";
//                                            break;
//                                        case "2":
//                                            cardName = "柴油";
//                                            break;
//                                        case "3":
//                                            cardName = "LNG";
//                                            break;
//                                        case "4":
//                                            cardName = "CNG";
//                                            break;
//                                    }
////                                    wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerCardUseRecordInfo.getCustomerName()+"，您好：\n" + "您在"+station.getStationName()+"的"+cardName+"电子卡充值成功信息如下"));
////                                    wxMpTemplate.add(new WxMpTemplateData("keyword1", electronicCardInfo.getCustomerNo()));
////                                    wxMpTemplate.add(new WxMpTemplateData("keyword2", amt + " 元"));
////                                    wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
////                                    wxMpTemplate.add(new WxMpTemplateData("keyword4", newBalance.toString()+ " 元"));
////                                    wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
////                                    wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ station.getStationName()+"的本次充值！"));
////                                    log.info("要推送的消息内容：" +wxMpTemplate.toString());
////                                    wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), customerCardUseRecordInfo.getBlogOpenid(), wxMpTemplate);
//
//                                    //新修订
//                                    WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
//                                    wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
//                                    wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
//                                    Map<String, WxTemplateData> templateDataMap = new HashMap<>();
//                                    templateDataMap.put("first",      WxTemplateData.builder().value("尊敬的"+customerCardUseRecordInfo.getCustomerName()+"您好：" + "您在"+station.getStationName()+"的"+cardName+"电子卡充值成功信息如下").build());
//                                    templateDataMap.put("keyword1",   WxTemplateData.builder().value(electronicCardInfo.getCustomerNo()).build());
//                                    templateDataMap.put("keyword2",   WxTemplateData.builder().value(amt + " 元").build());
//                                    templateDataMap.put("keyword3",   WxTemplateData.builder().value(presentAmt.toString()+ " 元").build());
//                                    templateDataMap.put("keyword4",   WxTemplateData.builder().value(newBalance.toString()+ " 元").build());
//                                    templateDataMap.put("keyword5",   WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
//                                    templateDataMap.put("remark",     WxTemplateData.builder().value("感谢您在"+ station.getStationName()+"的本次充值！").build());
//                                    wxTemplateMsg.setData(templateDataMap);
//                                    wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
//                                    log.info("===================================随行付本次电子卡充值流程结束===========================================");
//                                }
//                            }
//                        }
                }
            }
        }
    }


	@Override
	public int updateUserPresentAmt(Map<String, Object> map) {
		return electronicMembershipCardMapper.updateUserPresentAmt(map);
	}



    @Override
    public List<CustomerCardUseRecord> selectCustomerCardUseRecords(CustomerCardUseRecord customerCardUseRecord) {
        return electronicMembershipCardMapper.selectCustomerCardUseRecords(customerCardUseRecord);
    }

    @Override
    public CustomerCardUseRecord selectCustomerCardUseRecordByPhoneAndStationId(String phone, Long stationId) {
        return null;
    }

    @Override
    public int updateReturnCashById(CustomerElectronicCard customerElectronicCard) {
        return electronicMembershipCardMapper.updateReturnCashById(customerElectronicCard);
    }
}
